package cn.com.xcf.service.impl;

import cn.com.xcf.dao.mapper.TCheckIncomeMapper;
import cn.com.xcf.dao.model.TCheckIncome;
import cn.com.xcf.dao.model.TCheckIncomeDetail;
import cn.com.xcf.dao.model.TCheckIncomeDetailExample;
import cn.com.xcf.dao.model.TCheckIncomeExample;
import cn.com.xcf.service.CheckCostService;
import cn.com.xcf.service.IDGenerator;
import cn.com.xcf.service.TCheckIncomeDetailService;
import cn.com.xcf.service.TCheckIncomeService;
import cn.com.xcf.service.base.BaseServiceImpl;
import com.xcf.entity.Page;
import com.xcf.entity.system.User;
import com.xcf.util.PageData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TCheckIncomeService实现
 * @author WongBin
 * @date 2017/11/22.
 */
@Transactional(rollbackFor = Exception.class,propagation = org.springframework.transaction.annotation.Propagation.REQUIRED,readOnly=false)
//@Service(value="checkIncomeService")
public class TCheckIncomeServiceImpl extends BaseServiceImpl<TCheckIncomeMapper, TCheckIncome, TCheckIncomeExample> implements TCheckIncomeService {

    @Override
    public void initMapper() {
        super.mapper = checkIncomeMapper;
    }
    //@Autowired
    private TCheckIncomeMapper checkIncomeMapper;
    public void setCheckIncomeMapper(TCheckIncomeMapper tCheckIncomeMapper) {
        this.checkIncomeMapper = tCheckIncomeMapper;
    }

    @Autowired
    TCheckIncomeDetailService detailService;

    @Override
    public List getCheckUndoList(Object param, Map addition, Page page) {
        //PageData pd = new PageData();
        page.getPd().putAll(addition);
        return checkIncomeMapper.queryUndolistPage(page);
    }

    @Override
    public List getCheckList(TCheckIncome item,Map addition, Page page) {
        TCheckIncomeExample qry = new TCheckIncomeExample();
        qry.createCriteria();
        qry.setPage(page);
        return super.selectByPage(qry,addition,page);
    }

    @Override
    @Transactional
    public void addToCheckList(Object checkId, List undoList, Object operator) throws Exception {
        assert undoList!=null && undoList.size()>0;
        assert !ObjectUtils.isEmpty(checkId);

        final TCheckIncome check = mapper.selectByPrimaryKey(Long.valueOf(""+checkId));
        assert check!=null;

        undoList.forEach(item->{
            //添加对账明细数据
            TCheckIncomeDetail rec = new TCheckIncomeDetail();
            rec.setCheckId(Long.valueOf(checkId+""));
            //rec.setCreateBy(operator+"");
            //rec.setCreateTime(new java.util.Date());
            //id处理
            rec.setItemId(Long.valueOf(item+""));
            rec.setStatus(CheckIncomeStatus.APPEND.getFlag()+"");
            rec.setUpdateBy(operator+"");
            rec.setUpdateTime(new java.util.Date());
            detailService.insertSelective(rec);

            //对账金额累加
            //check.setCheckAmount(check.getCheckAmount().add(item.));
            //check.setUpdateBy(operator+"");
            //check.setUpdateTime(rec.getCreateTime());
            //updateByPrimaryKeySelective(check);
        });
        //修改对明细的状态为已对账
        resetItemStatus(checkId,undoList, CheckIncomeDetailStatus.CREATE.getFlag(),
                CheckIncomeDetailStatus.CANCEL.getFlag());
    }

    @Override
    @Transactional
    public void genCheckRecord(Map<String,Object> map,List undoList, Object operator) throws Exception {
        assert undoList!=null && undoList.size()>0;
        assert !ObjectUtils.isEmpty(operator);

        //final TCheckIncome check = this.selectByPrimaryKey(Integer.valueOf(""+checkId));
        //assert check!=null;
        User user = (User)operator;
        TCheckIncome check = new TCheckIncome();
        java.util.Date now = new java.util.Date();
        check.setUpdateBy(user.getUSER_ID());
        check.setUpdateTime(now);
        check.setCreateDate(now);
        check.setCheckDate(now);
        check.setCheckDept(user.getSKIN());
        check.setCheckDeptName(user.getSKIN());
        check.setCheckCode(IDGenerator.checkCode("checkInCome"));//?
        check.setCheckerId(user.getUSER_ID());
        check.setCheckerName(user.getNAME());
        check.setStatus(CheckIncomeStatus.CREATE.getFlag()+"");
      //对账金额累加
//        Map map = (Map) mapper.getUndoListItem(item.toString());
        
        check.setCheckRmbAmount(new BigDecimal(map.get("RMB").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
        
        check.setCheckUsdAmount(new BigDecimal(map.get("USD").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
        
        mapper.insertSelective(check);
        undoList.forEach(item->{
            //添加对账明细数据
            TCheckIncomeDetail rec = new TCheckIncomeDetail();
            rec.setCheckId(check.getId());
            rec.setCreateBy(user.getUSER_ID()+"");
            rec.setCreateTime(now);
            rec.setItemId(Long.valueOf(item+""));
            rec.setStatus(CheckIncomeStatus.APPEND.getFlag()+"");
            rec.setUpdateBy(user.getUSER_ID()+"");
            rec.setUpdateTime(rec.getCreateTime());
            detailService.insertSelective(rec);
          
            //修改费用明细的状态为已对账
            resetItemStatus(check.getId(),undoList, CheckIncomeDetailStatus.CREATE.getFlag(),
                    CheckIncomeDetailStatus.CANCEL.getFlag());
            
            
          
        });
       

    }

    @Override
    @Transactional
    public void cancelRecord(Object checkId, Object operator) throws Exception {
        TCheckIncome rec = mapper.selectByPrimaryKey(Long.valueOf(""+checkId));
        assert rec!=null;

        //费用明细状态回退
        resetItemStatus(checkId,null, CheckIncomeDetailStatus.CANCEL.getFlag(),
                CheckIncomeDetailStatus.CREATE.getFlag());

        TCheckIncomeExample ex = new TCheckIncomeExample();
        ex.createCriteria().andIdEqualTo(rec.getId());
        mapper.deleteByExample(ex);

        //核对明细回退
        TCheckIncomeDetail sel = new TCheckIncomeDetail();
        sel.setCheckId(rec.getId());
        /*sel.setStatus(CheckIncomeDetailStatus.CANCEL.getFlag()+"");
        sel.setUpdateBy(operator+"");
        sel.setUpdateTime(new Date());*/
        TCheckIncomeDetailExample selExample = new TCheckIncomeDetailExample();
        selExample.createCriteria().andCheckIdEqualTo(sel.getCheckId());
        //detailService.updateByExampleSelective(sel,selExample);
        detailService.deleteByExample(selExample);
    }

    @Override
    @Transactional
    public void invalidCheckRecordDetails(Object checkId, List detailIds, Object operator) throws Exception {
        TCheckIncome rec = mapper.selectByPrimaryKey(Long.valueOf(checkId+""));
        assert rec!=null;
        assert detailIds!=null && detailIds.size()>0;
        detailIds.forEach(item->{
            //核对明细回退
            TCheckIncomeDetailExample selExample = new TCheckIncomeDetailExample();
            selExample.createCriteria().andItemIdEqualTo(Long.valueOf(""+item));
            //detailService.updateByExampleSelective(sel,selExample);
            detailService.deleteByExample(selExample);
        });
        //收款明细解锁
        resetItemStatus(checkId,detailIds, CheckIncomeDetailStatus.CANCEL.getFlag(),
                CheckIncomeDetailStatus.CREATE.getFlag());
    }

    @Override
    public List listItemsByCheckId(Object checkId) {
        /*TCheckIncomeDetailExample e = new TCheckIncomeDetailExample();
        e.createCriteria().andCheckIdEqualTo(Long.valueOf(checkId+""));*/
        Map page = new HashMap();
        page.put("checkId",checkId);
        List data = mapper.queryDetailById(page);
        return data;
    }
    @Override
    public boolean resetItemStatus(Object checkId, List detailIs, int status, int currStatus) {
        Map param = new HashMap(4);
        if(checkId!=null && detailIs!=null){
            param.put("updateFlag",1);//按单个费用明细修改
            param.put("ids",detailIs);
            param.put("status",status);
            param.put("currStatus",currStatus);
            mapper.updateItemStatus(param);
            return true;
        }
        if(checkId!=null && detailIs==null){
            param.put("updateFlag",2);//按对账单号修改
            param.put("checkId",checkId);
            param.put("status",status);
            param.put("currStatus",currStatus);
            mapper.updateItemStatus(param);
            return true;
        }
        return false;
    }
    @Override
    public List exportUndoList(Map params) {
        return null;
    }

    @Override
    public List exportCheckList(Map params) {
        return null;
    }
    @Override
    public List getInvoiceDept(Page page){
    	
		return checkIncomeMapper.queryInvoiceDeptlistPage(page);
    	
    }
    @Override
    public List getFeeList(PageData pd){
    	return checkIncomeMapper.queryFeeListPage(pd);
    }
    @Override
    public Object getExchangeRate(){
    	return checkIncomeMapper.queryExchangeRate();
    }
    @Override
    public void updateDivFeeItems(List<PageData> list){
    	checkIncomeMapper.batchInsertDivFeeItems(list);
    	checkIncomeMapper.batchRemoveFeeItems(list);
    }
    @Override
    public void insertInvoiceApp(PageData pd){
    	checkIncomeMapper.insertInvoiceApp(pd);
    }
    @Override
    public Object getInvoiceAppCode(Map<String, Object> param)
    {
    	
       	checkIncomeMapper.getInvoiceAppCode(param);
    	return  param.get("invoiceAppCode");
    }
    @Override
    public List getopenTicketFeeType()
    {
    	return 	checkIncomeMapper.getopenTicketFeeType();
    }
    @Override
    public double getChangeTicketFee(int id)
    {
    	return 	checkIncomeMapper.getChangeTicketFee(id);
    }
    @Override
    public List getOpenTicketFeeItems(Object checkId)
    {
	    Map page = new HashMap();
	    page.put("checkId",checkId);
	    List data = mapper.getOpenTicketFeeItems(page);	   
        return data;
    }
    @Override
    public void insertInvoiceAppItem(Map<String,Object>map)
    {
    	 mapper.insertInvoiceAppItem(map);   
    }
}